<?php
/*
Copyright (C) 2009 de Flotte Maxence

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
?>
<?php
	/**
	* Generate SQL Writing Query (UPDATE and INSERT)
	*/

class ZzSQLWritingQueryGenerator {
	
	private $id;
	private $domain;
	private $type;
	private $update;
	
	private $isValidate = true;
	
	private $_tables = array();
	private $_fields = array();
	
	
	/**
	* Contructor
	* @param string $type the domain name
	* @param int|array $id the id of the row (optional). It could be an int (if the primary key is a collumn named id) or an array : array('key1' => 'value1', 'key2' => 'value2', ...).
	* @return void
	*/
	
	public function __construct($type,$id = null) {
		$this->type = $type;
		
		$domain = 'Dom'.$type;
		$this->domain = new $domain();
		
		if(!is_null($id)) {
			if(!is_array($id)) {
				$id = array('id' => $id);
			}
			$this->update = true;
		}
		else
			$this->update = false;
		$this->id = $id;
	}
	
	/**
	* Set a new field
	* @param string $field name of the field
	* @param int $value the new value
	* @return bool true if all is ok, else false
	*/
	public function set($field,$value) {
		$this->isValidate = false;
		if($this->domain->$field->setValue($value)) {
			if(!isSet($this->_tables[$this->domain->$field->dom]))
				$this->_tables[$this->domain->$field->dom] = array();
			$this->_tables[$this->domain->$field->dom][$field] = $value;
			$this->_fields[$field] = $value;
			return true;
		}
		return false;
	}
	
	/**
	* Validate data
	* @return bool true if all is ok, else false
	
	*/
	public function validate() {
		//Check not nullable rows
		if(!$this->update) {
			foreach($this->domain as $field => $domtype) {
				if(!$domtype->nullable)
					if(empty($this->_fields[$field]))
						return false;
			}
		}
		else {
			foreach($this->_fields as $field => $value) {
				if(empty($value))
					if(!$this->domain->$field->nullable)
						return false;
			}
		}
		//Check Primary key (pk)
		$_pk = array();
		foreach($this->domain as $fieldName => $field) {
			if(strToLower(get_parent_class($field)) == 'domtype') {
				if($field->primary)
					$_pk[] = $fieldName;
			}
		}
		if($this->update) {
			foreach($_pk as $key)
				if(empty($this->id[$key]))
					return false;
		}
		else {
			$_pk = array();
			if(count($_pk) > 1) {
				$this->id = $_pk;
				//Pk are provide ?
				foreach($_pk as $key => $val) {
					if(empty($this->domain->$key->value))
						return false;
				}
			}
		}
		$this->isValidate = true;
		return true;
	}
	
	/**
	* Save data
	* @return bool true if all is ok, else false
	*/
	public function save() {
			if(!$this->isValidate) {
				if(!$this->validate())
					return false;
			}
			if($this->update)
				foreach($this->_tables as $tableName => $table) {
					$query = 'UPDATE `'.$GLOBALS['prefix'].$tableName.'` SET';
					$_value = array();
					$first = true;
					foreach($table as $field => $value) {
						if($first)
							$first = false;
						else
							$query .= ',';
						$query .= ' `'.$this->domain->$field->name.'` = ?';
						$_value[] = $value; 
					}
					$query .= ' WHERE ';
					foreach($this->id as $name => $value) {
						$query .= '`'.$name.'` = ?';
						$_value[] = $value; 
					}
// 					echo $query;
// 					print_r($_value);
					ZzSQL::exec($query,$_value);
				}
			else
				foreach($this->_tables as $tableName => $table) {

					$query = 'INSERT INTO `'.$GLOBALS['prefix'].$tableName.'`(';
					$endQuery = 'VALUES(';
					$_value = array();
					
					if(isSet($this->id))
						foreach($this->id as $key => $val) {
							$table[$key] = $this->domain->$key->value;
						}
	
					$first = true;
					foreach($table as $field => $value) {
						if($first)
							$first = false;
						else {
							$query .= ',';
							$endQuery .= ',';
						}
						$query .= '`'.$this->domain->$field->name.'`';
						$endQuery .= '?';
						$_value[] = $this->domain->$field->value; 
					}
					
					
					$query = $query.') '.$endQuery.');';

// 					echo $query;
// 					print_r($_value);
					ZzSQL::exec($query,$_value);
					
					
					if(!isSet($this->id) and isSet($this->domain->id)) {
						$id = ZzSQL::lastInsertId();
						$this->id = array('id' => $id);
						$this->set('id',$id);
					}
				}
	}
	
	/**
	* Remove data
	* @return bool true if all is ok, else false
	*/
	public function remove() {
		return $this->rm();
	}
	
	/**
	* Remove data
	* @return bool true if all is ok, else false
	*/
	public function rm() {
		//Check primary keys
		$_pk = array();
		foreach($this->domain as $fieldName => $field) {
			if(strToLower(get_parent_class($field)) == 'domtype') {
				if($field->primary)
					$_pk[] = $fieldName;
			}
		}
		foreach($_pk as $key)
			if(empty($this->id[$key]))
				return false;
		
		foreach($this->_tables as $tableName => $table) {
			$query = 'DELETE FROM `'.$GLOBALS['prefix'].$tableName.'` WHERE';
			$first = true;
			foreach($this->id as $name => $value) {
				if($first)
					$first = true;
				else
					$query .= 'AND';
				$query .= ' `'.$name.'` = ?';
				$_value[] = $value;
			}
			
//  					echo $query;
//  					print_r($_value);
					ZzSQL::exec($query,$_value);
		}
		
	}
}
?>